import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '../views/system/Home/index.vue'
import Layout from '@/layout/index.vue'
import { transformRoutes } from '@/utils/routeUtils'
const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: 'layout',
      component: Layout,
      children: [
        {
          path: '/',
          redirect: '/home'
        }
        ,
        {
          path: 'home',
          name: 'home',
          component: HomeView,
        }, {
          path: '/:pathMatch(.*)*',
          name: '404',
          component: () => import("@/views/error/404.vue")
        }
      ]
    },

    {
      path: '/login',
      name: 'login',
      component: () => import('@/views/LoginView.vue')
    },
    {
      path: '/register',
      name: 'register',
      component: () => import('@/views/RegisterView.vue')
    },
    {
      path: '/:pathMatch(.*)*',
      component: () => import("@/views/error/404.vue")
    }
  ],
})
router.beforeEach((to, from, next) => {
  try {
    const Menus = JSON.parse(localStorage.getItem("menu") || "");
    if (Menus !== "" || Menus !== undefined || Menus !== null) {
      const dynamicRoutes = transformRoutes(Menus);
      // 添加动态路由
      dynamicRoutes.forEach((route) => {
        router.addRoute("layout", route);
      });
    }

  } catch (E) {
    console.log(E);
  }
  next()
})
export default router
